<?php

declare(strict_types=1);
/**
 * This file is part of MoChat.
 * @link     https://mo.chat
 * @document https://mochat.wiki
 * @contact  group@mo.chat
 * @license  https://github.com/mochat-cloud/mochat/blob/master/LICENSE
 */
namespace MoChat\Plugin\SystemHelp\Logic;

use Hyperf\Contract\StdoutLoggerInterface;
use Hyperf\DbConnection\Db;
use Hyperf\Di\Annotation\Inject;
use MoChat\Framework\Constants\ErrorCode;
use MoChat\Framework\Exception\CommonException;
use MoChat\Plugin\SystemHelp\Contract\SystemHelpContract;

class UpdateLogic
{
    /**
     * @Inject
     * @var SystemHelpContract
     */
    protected $systemHelpService;

    /**
     * @Inject
     * @var StdoutLoggerInterface
     */
    protected $logger;

    public function handle($params): array
    {
        if (! empty($this->systemHelpService->getSystemHelpByCorpIdMenuIdIsDefault($params['corpId'], $params['menuId'], $params['id']))) {
            throw new CommonException(ErrorCode::INVALID_PARAMS, '菜单已存在默认链接，不可操作');
        }
        // 参数
        $data = [
            'name' => $params['name'],
            'url' => $params['url'],
        ];
        // 数据操作
        Db::beginTransaction();
        try {
            # # 创建活动
            $id = $this->systemHelpService->updateSystemHelpById($params['id'], $data);
            Db::commit();
        } catch (\Throwable $e) {
            Db::rollBack();
            $this->logger->error(sprintf('%s [%s] %s', '链接修改失败', date('Y-m-d H:i:s'), $e->getMessage()));
            $this->logger->error($e->getTraceAsString());
            throw new CommonException(ErrorCode::SERVER_ERROR, $e->getMessage()); // '活动创建失败'
        }
        return [];
    }
}
